package com.atguigui.webfluxdemo2.service.impl;


import com.atguigui.webfluxdemo2.entity.User;
import com.atguigui.webfluxdemo2.service.UserService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    //创建map集合存储数据
    private final Map<Integer, User> userMap = new HashMap<>();


    public UserServiceImpl() {
        this.userMap.put(1, new User("lucy", "women", 20));
        this.userMap.put(2, new User("mary", "men", 30));
        this.userMap.put(3, new User("jack", "women", 50));
    }

    //根据id查询
    @Override
    public Mono<User> getUserById(int id) {
        return Mono.justOrEmpty(this.userMap.get(id));
    }

    //查询多个元素
    @Override
    public Flux<User> getAllUser() {
        return Flux.fromIterable(this.userMap.values());
    }

    //添加用户
    @Override
    public Mono<Void> saveUserInfo(Mono<User> userMono) {
        return userMono.doOnNext(person -> {
            //想map集合中存值
            int id = userMap.size()+1;
            userMap.put(id, person);
        }).thenEmpty(Mono.empty()); //终止信号
    }
}
